package utils

import (
	"encoding/json"
	"fmt"
	"log"
	"math/big"
	"strconv"
	"unicode/utf8"
)

func Int2Str(value int) string {
	return strconv.Itoa(value)
}

func Str2Int(value string) int {
	result, _ := strconv.Atoi(value)
	return result
}

func Int642Str(value int64) string {
	return strconv.FormatInt(value, 10)
}

func Str2Int64(value string) int64 {
	number, err := strconv.ParseInt(value, 10, 64)
	if err != nil {
		log.Println("输入非法字符：", err)
		return 0
	}
	return number
}

func Any2Int64(value any) int64 {
	switch v := value.(type) {
	case int:
		return int64(v)
	case int8:
		return int64(v)
	case int16:
		return int64(v)
	case int32:
		return int64(v)
	case int64:
		return v
	case uint:
		return int64(v)
	case uint8:
		return int64(v)
	case uint16:
		return int64(v)
	case uint32:
		return int64(v)
	case uint64:
		return int64(v)
	case float32:
		return int64(v)
	case float64:
		return int64(v)
	case string:
		number, err := strconv.ParseInt(v, 10, 64)
		if err != nil {
			log.Println("无法转为Int64：", value, "err:", err)
			return 0
		}
		return number
	default:
		log.Println("无法转为Int64：", value, "type:", fmt.Sprintf("%T", value))
		return 0
	}
}

func Float642Str(value float64) string {
	return strconv.FormatFloat(value, 'f', -1, 64)
}

func Str2Float64(value string) float64 {
	number, err := strconv.ParseFloat(value, 64)
	if err != nil {
		log.Println("输入非法字符：", err)
		return 0
	}
	return number
}

func Any2Float64(value any) float64 {
	switch v := value.(type) {
	case int:
		return float64(v)
	case int8:
		return float64(v)
	case int16:
		return float64(v)
	case int32:
		return float64(v)
	case int64:
		return float64(v)
	case uint:
		return float64(v)
	case uint8:
		return float64(v)
	case uint16:
		return float64(v)
	case uint32:
		return float64(v)
	case uint64:
		return float64(v)
	case float32:
		return float64(v)
	case float64:
		return v
	case string:
		number, err := strconv.ParseFloat(v, 64)
		if err != nil {
			log.Println("无法转为Float64：", value, "err:", err)
			return 0
		}
		return number
	default:
		log.Println("无法转为Float64：", value, "type:", fmt.Sprintf("%T", value))
		return 0
	}
}

func BigInt2Float64(value *big.Int) float64 {
	bigFloatValue := new(big.Float).SetInt(value)
	floatValue, _ := bigFloatValue.Float64()
	return floatValue
}

func Float642BigInt(value float64) *big.Int {
	bigFloatValue := new(big.Float).SetFloat64(value)
	result, _ := bigFloatValue.Int(nil)
	return result
}

func Str2Bool(value string) bool {
	flag, err := strconv.ParseBool(value)
	if err != nil {
		log.Println("输入非法字符：", err)
		return false
	}
	return flag
}

func Map2Bytes(data any) (result []byte) {
	result, err := json.Marshal(data)
	if err != nil {
		log.Println("Map2Bytes() 失败：", err)
	}
	return
}

func Bytes2Map(data []byte) (result map[string]any) {
	err := json.Unmarshal(data, &result)
	if err != nil {
		log.Println("Bytes2Map() 失败：", err)
	}
	return
}

// 字符串长度
func StrLen(str string) int {
	return utf8.RuneCountInString(str)
}
